<template>
  <!-- <el-table-column type="selection" width="55" /> -->
  <el-table
    ref="tableRef"
    v-loading="loading"
    :data="list"
    row-key="id"
    calss="orderTable"
    cell-class-name="tableCell"
    row-class-name="tableRow"
    :span-method="spanMethod"
    @selection-change="handleSelectionChange"
    height="80vh"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column class-name="mergeRow" width="1">
      <template #default="{ row }">
        <div class="relative flex">
          <span
            class="ml-10px text-[#231E47] text-[14px] cursor-pointer mr-20px py-[8px] font-normal"
            v-copyText="row.orderNo"
          >
            订单号：{{ row.orderNo }}
            <Icon icon="ep:copy-document" :size="12" class="cursor-pointer" />
          </span>
          <span class="mr-20px flex items-center text-[#231E47] text-[14px] py-[8px] font-normal">
            下单链接：
            <el-tooltip width="200px" placement="top">
              <template #content>
                <div class="w-[300px] text-[12px] text-[#fff] cont">
                  {{ row.orderLink || '-' }}
                </div>
              </template>
              <div class="cursor-pointer text-[#077BFF] text-cut max-w-[300px]" @click="openUrl(row.orderLink)">
                {{ row.orderLink || '-' }}
              </div>
            </el-tooltip>
          </span>
          <span class="mr-20px text-[#231E47] text-[14px] py-[8px] font-normal">
            创建时间：
            {{ formatDate(row.createTime) }}
          </span>
          <span
            class="mr-20px text-[#231E47] text-[14px] py-[8px] font-normal"
            v-if="row.updateTime"
          >
            更新时间：
            {{ formatDate(row.updateTime) }}
          </span>
          <span class="mr-20px text-[#231E47] text-[14px] py-[8px] cursor-pointer font-normal hover:text-[#077BFF]" @click="handelHistory(row)">
            历史购买情况：已下单{{ row.totalOrders || 0 }}次，签收{{ row.receivedOrders || 0 }}次
          </span>
        </div>
        <!-- <div
            class="ml-auto flex justify-between shrink-0 items-center w-[160px] text-[14px] font-normal right-[20px] px-[10px] btn py-[8px] btnfixed"
          >
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">编辑</span>
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">详情</span>
            <span class="text-[#3721FF] pl-[12px] cursor-pointer">备注</span>
          </div> -->
      </template>
    </el-table-column>
    <el-table-column label="商品信息" min-width="300">
      <template #default="{ row }">
        <div class="mt-[35px] overflow-hidden" :class="row.isExpland ? 'noMaxH' : 'max-h-[120px]'">
          <div class="flex items-center info">
            <div class="w-[86px] h-[86px] mr-[10PX] left">
              <el-image
                  :src="row.cover"
                  class="!h-[86px] !w-[86px] roundec-[12px]"
                  fit="contain"
                  @click="imagePreview(row.cover)"
                >
                  <template #error>
                    <div class="image-slot">
                      <icon icon="ep:picture" />
                    </div>
                  </template>
                </el-image>
            </div>
            <div class="right">
              <div class="text-[14px] text-[#dfc437] pt-[8px]">{{ row.thaliName }}</div>
              <div class="flex pt-[4px] pb-[4px]  flex-wrap" v-for="(item, index) in row.detailList" :key="index" :style="index < row.detailList.length - 1 ? 'border-bottom:1px dashed #999' : ''">
                  <div class="cursor-pointer info"  @click="openUrl(row.orderLink)">
                    <!-- <ElTooltip :content="item.productName" placement="top"> -->
                      <!-- overflow-ellipsis -->
                      <div class="text-cut text-[12PX] w-[180PX] text-[#077BFF]">
                        {{item.code}} - {{ item.productName }}
                      </div>
                    <!-- </ElTooltip> -->
                    <div class="flex items-center  text-[12px] numbox"> <span class="text-[#231E47]">({{item.sku}})</span> * <span class="text-[#999]">{{ item.number }}</span> </div>
                    <!-- <div class="text-[#999] text-[14px] numbox"> 商品ID: {{ item.productId }} </div> -->
                  </div>
              </div>
            </div>
          </div>
          
        </div>
        <div class="cursor-pointer text-[#077BFF]" @click="changeExpland(row)"> {{ row.isExpland ? '收起' : '展开' }}</div>
      </template>
    </el-table-column>
    <el-table-column label="IP地址" width="150" prop="ipAddress">
      <template #default="{ row }">
        <div class="pt-[30px]">
          <div
              class="tag"
              v-for="(item, index) in stringToArray(row.ipAddress)"
              :key="index"
            >
              <div :class="index===0?'underline':''" v-if="index < stringToArray(row.ipAddress).length - 1">
                {{ item }}
              </div>
              <div class="text-[12px] text-[#999]" v-else>
                {{ item }}
              </div>
            </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="地区/来源" width="120" prop="areaName" >
      <template #default="{ row }">
        {{ row.areaName||'-' }}/{{ row.source||'-' }}
      </template>
    </el-table-column>

    <el-table-column label="下单信息" min-width="250">
      <template #default="scope">
        <div class="pt-[30px]">
          <div>买家：{{ scope.row.customerName }}</div>
          <div>买家手机：{{ scope.row.customerPhone }}</div>
          <div class="">
            <img :src="StarPng" class="w-[14px] h-14px" alt="" v-if="scope.row.remoteFlag" />
            地址：{{ scope.row.detailAddress }}{{ scope.row.houseNumber }}
          </div>
        </div>
        <!-- 快递发货  -->
        <div v-if="scope.row.deliveryType === DeliveryTypeEnum.EXPRESS.type" class="flex flex-col">
          <span>买家：{{ scope.row.user?.nickname }}</span>
          <span>
            收货人：{{ scope.row.receiverName }} {{ scope.row.receiverMobile }}
            {{ scope.row.receiverAreaName }} {{ scope.row.receiverDetailAddress }}
          </span>
        </div>
        <!-- 自提  -->
        <div v-if="scope.row.deliveryType === DeliveryTypeEnum.PICK_UP.type" class="flex flex-col">
          <span>
            门店名称：
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.name }}
          </span>
          <span>
            门店手机：
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.phone }}
          </span>
          <span>
            自提门店:
            {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.detailAddress }}
          </span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="物流方式" prop="logisticsMethodName" min-width="120" />

    <!-- <dict-tag :type="DICT_TYPE.TRADE_DELIVERY_TYPE" :value="scope.row.deliveryType" />  原物流方式-->

    <el-table-column label="订单总金额" min-width="120">
      <template #default="{ row }"> 
      <div>{{ row.currencySymbol }} {{ row.orderAmount }} </div>
      <div v-if="row.orderFreight " class="text-[12px] text-[#666]">(含运费{{ row.currencySymbol }} {{ row.orderFreight }})</div>  
      <div>￥ {{ row.orderAmountCny || '-' }}</div>
      </template>
    </el-table-column>
    <el-table-column label="审核建议" width="180" v-if="status === 1 || status === 2">
      <template #default="{ row }">
     
        <div class=" mt-[30px] overflow-hidden" :class="row.isExpland ? 'noMaxH' : 'max-h-[90px]'">
          <div
            class="tag"
            v-for="(item, index) in stringToArray(row.auditSugget)"
            :key="index"
            @click="handleAuditSugget(row, item)"
          >
            <div :class="getClass(item)">
              {{ item }}
            </div>
          </div>
        </div>
        <div class="cursor-pointer text-[#077BFF]" @click="changeExpland(row)"> {{ row.isExpland ? '收起' : '展开' }}</div>
      </template>
    </el-table-column>
    <el-table-column label="部门/人员" width="180">
      <template #default="{ row }">
        <div>{{ `${row.deptName||'-'}/${row.createName||'-'}` }}</div>
       
      </template>
    </el-table-column>
    <el-table-column label="留言/备注" min-width="280" show-overflow-tooltip>
      <template #default="{ row }">
        <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
        <div class="flex items-start items">
          <div class="shrink-0 label">留言：</div>
          <div class="val">{{ row.message }}</div>
        </div>
        <div class="flex items-start items">
          <div class="shrink-0 label">备注：</div>
          <div class="val">{{ row.remark }}</div>
        </div>
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="状态" width="160" align="center" class-name="btnColumn">
      <template #default="scope">
        <div
          class="ml-auto flex items-center w-[160px] px-[15px] mb-[10px] top-[8px] absolute text-[12px] font-normal btn"
          v-if="status != 1 && status != 3"
        >
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handleEdit(scope.row)"
            v-if="scope.row.status != 9 && scope.row.status != 8"
          >
            编辑
          </div>
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handleDetails(scope.row)"
          >
            详情
          </div>
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handelRemark(scope.row)"
          >
            备注
          </div>
          <div
            class="text-[#3721FF] text-[12px] cursor-pointer mr-[10px]"
            @click="handleRowStatus(scope.row, 'uninvalid')"
            v-if="scope.row.status == 9"
          >
            反无效
          </div>
          <el-dropdown
            placement="bottom"
            size="small"
            v-if="
              scope.row.status == 4 ||
              scope.row.status == 5 ||
              scope.row.status == 7 ||
              scope.row.status == 8 ||
              scope.row.status == 6
            "
          >
            <span class="text-[#3721FF] cursor-pointer text-[12px]">更多</span>
            <template #dropdown>
              <!-- <el-dropdown-menu class="dark-dropdown">
                <el-dropdown-item>物流查询</el-dropdown-item>
                <el-dropdown-item>异常订单</el-dropdown-item>
                <el-dropdown-item>变更未签收</el-dropdown-item>
                <el-dropdown-item>变更已签收</el-dropdown-item>
              </el-dropdown-menu> -->
              <div
                class="bg-[#2B1D3D] w-[100px] px-[14px] rounded-[4px] py-[7px] menulist"
                v-if="
                  scope.row.status == 4 ||
                  scope.row.status == 5 ||
                  scope.row.status == 6 ||
                  scope.row.status == 7 ||
                  scope.row.status == 8
                "
              >
                <!-- <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  @click="handleLogistics"
                >
                  物流查询
                </div> -->
                <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  v-if="scope.row.status == 4"
                  @click="handleRowStatus(scope.row, 'sends')"
                >
                  强制发货
                </div>
                <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  v-if="scope.row.status == 5"
                  @click="handleRowStatus(scope.row, 'abnormal')"
                >
                  异常订单
                </div>
                <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  v-if="scope.row.status == 5 || scope.row.status == 6"
                  @click="handleRowStatus(scope.row, 'unsigned')"
                >
                  变更未签收
                </div>
                <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  v-if="scope.row.status == 5 || scope.row.status == 7"
                  @click="handleRowStatus(scope.row, 'signed')"
                >
                  变更已签收
                </div>
                <div
                  class="text-[12px] text-[#999] py-[2px] cursor-pointer menu hover:text-[#fff]"
                  v-if="scope.row.status == 8"
                  @click="handleRowStatus(scope.row, 'unabnormal')"
                >
                  反异常
                </div>
              </div>
            </template>
          </el-dropdown>
        </div>
        <div class="flex justify-center items-center statusbox">
          <div
            class="px-[7px] py-[2px] flex items-center rounded-[5px]"
            :style="`background-color:${orderStatus[scope.row.status].bgColor}`"
          >
            <div class="w-[12px] h-[12px] rounded-[50%] relative mr-[4px] icon">
              <img
                :src="orderStatus[scope.row.status].icon"
                class="w-full h-full object-contain absolute top-0 left-0"
              />
            </div>
            <div
              class="text-[12px] status txt"
              :style="`color:${orderStatus[scope.row.status].color}`"
            >
              {{ orderStatus[scope.row.status].name }}</div
            >
          </div>
        </div>

        <!-- <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" /> -->
      </template>
    </el-table-column>
  </el-table>
  <OrderDetails ref="orderDetailsRef" :orderNo="curOrderId" />
  <OrderEdit ref="orderEditRef" :editOrderNo="editCurOrderId" @updateList="updateTable" />
  <Logistics ref="logisticsRef" />
  <Remark
    ref="remarkRef"
    :remarkOrderNo="remarkOrderId"
    :remarkInfo="remarkInfo"
    @updateRemark="updateRemark"
  />
  <AuditList
    ref="auditListRef"
    :orderNo="curOrderId"
    :curAuditStr="curAuditStr"
    @updateOrderStatus="updateOrderStatus"
    @clearSelect="clearSelect"
  />
  <OrderHistroy ref="orderHistroyRef" :curRow="curRow" />
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2, stringToArray } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore'
import { orderStatus } from '@/utils/order'

import OrderDetails from './OrderDetails.vue'
import OrderEdit from './OrderEdit.vue'
import Logistics from './Logistics.vue'
import Remark from './Remark.vue'
import AuditList from './AuditList.vue'
import OrderHistroy from './OrderHistroy.vue'
import StarPng from '@/assets/mall/trade/order/star.png'

import { usePageLoading } from '@/hooks/web/usePageLoading'
import { win32 } from 'path'

const { loadStart, loadDone } = usePageLoading()

defineOptions({ name: 'OrderTableColumn' })

const emit = defineEmits([
  'updateList',
  'selectionChange',
  'showActionDialog',
  'updateOrderStatus',
  'clearSelect'
])

const props = defineProps<{
  list: OrderVO[]
  pickUpStoreList: DeliveryPickUpStoreVO[]
  status: number
}>()

const loading = ref(false)

const tableRef = ref<TableInstance>()

const curOrderId = ref()

const curRow = ref();

const editCurOrderId = ref()

const remarkOrderId = ref()

const remarkInfo = ref()

const curAuditStr = ref('')

const orderDetailsRef = ref<InstanceType<typeof OrderDetails> | null>(null)

const orderEditRef = ref<InstanceType<typeof OrderEdit> | null>(null)

const logisticsRef = ref<InstanceType<typeof Logistics> | null>(null)

const remarkRef = ref<InstanceType<typeof Remark> | null>(null)

const auditListRef = ref<InstanceType<typeof AuditList> | null>(null)

const orderHistroyRef = ref<InstanceType<typeof OrderHistroy> | null>(null)

const headerStyle = ({ row, columnIndex }: any) => {
  // 表头第一行第一列占 8
  if (columnIndex === 0) {
    row[columnIndex].colSpan = 8
  } else {
    // 其余的不要
    row[columnIndex].colSpan = 0
    return {
      display: 'none'
    }
  }
}

const selectAll = ref(false)
const selectAllIndeterminate = ref(false)
const selectedRows = ref<any[]>([])

interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  // const len = props.list.find(
  //   (order) => order.items?.findIndex((item) => item.id === row.id) !== -1
  // )?.items?.length
  // const len = 8
  // // 要合并的列，从零开始
  // const colIndex = [3, 4, 5, 6, 7]
  // if (colIndex.includes(columnIndex)) {
  //   // 除了第一行其余的不要
  //   if (rowIndex !== 0) {
  //     return {
  //       rowspan: 0,
  //       colspan: 0
  //     }
  //   }
  //   // 动态合并行
  //   return {
  //     rowspan: len!,
  //     colspan: 1
  //   }
  // }
  if (columnIndex === 7) {
    return [1, 1] // 第一列合并所有行
  }
  return [1, 1] // 其他列正常显示
}

/** 解决 ref 在 v-for 中的获取问题*/
const setOrderTableRef = (el: TableInstance) => {
  if (!el) return
  // 只要第一个表也就是开始的第一行
  if (el.tableId !== 'el-table_2') {
    return
  }
  tableHeadWidthAuto(el)
}
// 头部 col 宽度初始化
const orderTableHeadWidthList = ref([300, 150, 120, 160, 120, 120, 120, 160])
// 头部宽度自适应
const tableHeadWidthAuto = (el: TableInstance) => {
  const columns = el.store.states.columns.value
  if (columns.length === 0) {
    return
  }
  columns.forEach((col: TableColumnCtx<TableInstance>, index: number) => {
    if (col.realWidth) {
      orderTableHeadWidthList.value[index] = col.realWidth
    }
  })
}

/**
 * 获取单元格样式
 */
const getClass = (item: string) => {
  // 使用正则表达式检查
  return /\(\d+\)/.test(item) ? 'text-[#077BFF] cursor-pointer' : ''
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/**
 * 全选切换
 */
const handleSelectAll = () => {
  const allSelected = selectAll.value // 获取全选状态
  selectAllIndeterminate.value = false
  selectedRows.value = allSelected
    ? props.list.map((order) => {
        return order
      })
    : [] // 取消所有选中
  // 更新每个订单的选中状态
  props.list.forEach((order) => {
    order.selected = allSelected
  })
}

/**
 * 显示用户历史订单
*/
const handelHistory = (row: any) => {
  curRow.value = row
  orderHistroyRef.value?.show()
}


/**
 * 单选选中切换
 */
const handleSelectItems = (row) => {
  const allSelected = props.list.every((order) => order.selected)
  selectAll.value = allSelected

  // 更新 indeterminate 状态
  const someSelected = props.list.some((order) => order.selected)
  selectAllIndeterminate.value = someSelected && !allSelected
}

/**
 * 显示详情
 */
const handleDetails = (row) => {
  curOrderId.value = row.orderNo
  orderDetailsRef.value?.show()
}

/**
 * 物流查询
 */
const handleLogistics = (row) => {
  curOrderId.value = row.orderNo
  editCurOrderId.value = row.orderNo
  logisticsRef.value?.show()
}

/**
 * 显示编辑
 */
const handleEdit = (row) => {
  editCurOrderId.value = row.orderNo
  orderEditRef.value?.show()
}

/**
 * 显示备注
 */
const handelRemark = (row) => {
  remarkOrderId.value = row.orderNo
  remarkInfo.value = row.remark
  remarkRef.value?.show()
}

const openUrl = (url: string) => {
  //校驗url
  if(!url) return
  if( url.indexOf('http') > -1 || url.indexOf('https') > -1){
    window.open(url)
  }else{
    ElMessage.error('链接不合法')
  }
}
/**
 * 展开/收起
*/
const changeExpland = (row) => {
  row.isExpland = !row.isExpland
}

const updateTable = () => {
  emit('updateList')
}

/**
 * 修改备注
 */
const updateRemark = async (val: any) => {
  try {
    loadStart()
    await TradeOrderApi.updateOrderRemarkNew({ orderNo: val.orderNo, remark: val.remark })
    ElMessage.success('备注修改成功')
    emit('updateList', val)
  } catch (error) {
  } finally {
    remarkRef.value?.hide()
    loadDone()
  }
}
/**
 * 审核建议数据提交
 */
const updateOrderStatus = (value: any, action: string) => {
  emit('updateOrderStatus', value, action)
  setTimeout(() => {
    auditListRef.value?.getList()
  }, 1200);
}
/**
 * 清空审核建议选中的数据
 */
const clearSelect = () => {
  emit('clearSelect')
}

/**
 * 显示审核建议侧边栏
 */

const handleAuditSugget = (row: any, str: string) => {
  //待实现
  const regex = /\(\d+\)/
  if (regex.test(str)) {
    curOrderId.value = row.orderNo
    curAuditStr.value = str
    auditListRef.value?.show()
  }
}
/**
 * 单选数据操作
 */
const handleRowStatus = (row: any, actionName: string) => {
  tableRef.value?.clearSelection()
  props.list.map((item) => {
    if (item === row) {
      tableRef.value?.toggleRowSelection(item, true)
    }
  })
  emit('showActionDialog', actionName)
}

/**
 * 获取选中行信息
 */
const handleSelectionChange = (val) => {
  selectedRows.value = val
  emit('selectionChange', val)
}

const closeAudit = () => {
  auditListRef.value?.hide()
}
defineExpose({
  closeAudit
})
</script>
<style lang="scss" scoped>
.noMaxH{
  max-height: unset !important;
}
.dark-dropdown {
  background-color: #333; /* 深色背景 */
  color: white !important; /* 字体颜色 */
  .el-dropdown-menu__item {
    color: #fff !important;
  }
}

/* 如果需要改变悬停时的颜色 */
.dark-dropdown .el-dropdown-item:hover {
  background-color: #fff; /* 悬停时的背景颜色 */
}
</style>
